package com.ksyun.onepass.controller;

import com.ksyun.onepass.domain.common.QueryUserAmountRequest;
import com.ksyun.onepass.domain.common.SearchResponse;
import com.ksyun.onepass.domain.po.User;
import com.ksyun.onepass.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@RequestMapping()
@RestController
@Slf4j
public class SearchController {
    @Autowired
    private UserService userService;
    private final ExecutorService executorService;
    private final BlockingQueue<Future<List<User>>> queryQueue;

    public SearchController(UserService userService) {
        this.userService = userService;
        this.executorService = Executors.newFixedThreadPool(100); // 你可以根据需求调整线程池大小
        this.queryQueue = new LinkedBlockingQueue<>();
    }

    @PostMapping("/onePass/queryUserAmount")
    public ResponseEntity<SearchResponse> queryUserAmount(
            @RequestHeader(value = "X-KSY-REQUEST-ID") String requestId,
            @RequestBody List<Long> uids) {

        // 提交查询任务到线程池
        Future<List<User>> future = executorService.submit(() -> userService.queryUserAmounts(uids));
        queryQueue.add(future);

        // 处理查询结果
        List<User> userAmounts = getQueryResults();

        SearchResponse response = new SearchResponse(200, userAmounts, requestId, "ok");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    private List<User> getQueryResults() {
        List<User> userAmounts = new ArrayList<>();

        // 从队列中获取查询结果
        while (!queryQueue.isEmpty()) {
            Future<List<User>> future = queryQueue.poll();

            try {
                if (future != null) {
                    // 获取查询结果
                    userAmounts.addAll(future.get());
                }
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常
                e.printStackTrace();
            }
        }

        return userAmounts;
    }

    // 关闭线程池（可以在适当的时机调用，比如应用关闭时）
    public void shutdown() {
        executorService.shutdown();
    }
}
